package dao;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class DataBaseConnection implements IConnection {
	private Connection connection;
	private static Properties properties;

	public DataBaseConnection() throws ClassNotFoundException, IOException {
		loadProperties();
		loadDriver();
	}

	@Override
	public void closeConnection() {
		try {
			if (!connection.isClosed())
				connection.close();
		} catch (SQLException ex) {
			ex.printStackTrace();
			System.out.println("Error while closing: " + ex.getMessage());
		}
	}

	@Override
	public Connection getConnection() {
		try {
			connection = DriverManager.getConnection(properties.getProperty("url"), properties
					.getProperty("user"), properties.getProperty("password"));
		} catch (Exception ex) {
			ex.printStackTrace();
			System.out.println("Error while getting connection: " + ex.getMessage());
		}
		return connection;
	}

	private void loadDriver() throws ClassNotFoundException, IOException {
		Class.forName(properties.getProperty("driver"));
	}
	
	private void loadProperties() throws IOException {
		properties = new Properties();
		properties.load(getClass().getResourceAsStream("/database.properties"));
	}
}
